package com.lqjava.tuxiaowang.tuxiaowang.customerapp.app.sdk.ali;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;

import com.lqjava.tuxiaowang.tuxiaowang.beans.entity.request.ALIPayOAuthLoginRequest;
import com.lqjava.tuxiaowang.tuxiaowang.beans.entity.response.OTherUserResponse;
import com.lqjava.tuxiaowang.tuxiaowang.beans.enums.UserTypeEnums;
import com.lqjava.tuxiaowang.tuxiaowang.customerapp.app.sdk.ali.beans.AlipayUser;
import com.lqjava.tuxiaowang.tuxiaowang.customerapp.app.sdk.ali.props.ALIPayProps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ALIPaySDK  implements InitializingBean {

	@Autowired
	StringRedisTemplate redis;
	
	@Autowired
    ALIPayProps props;
	
    /**Alipay客户端*/
    private AlipayClient alipayClient;
    
    
	@Override
	public void afterPropertiesSet() throws Exception {
		
		String border = props.getBorder();
		String appId = props.getAppId();
		String privateKey = props.getPrivateKey();
		String publicKey = props.getPublicKey();
		alipayClient = new DefaultAlipayClient(border, appId, privateKey, "json", "UTF-8", publicKey, "RSA2");
	}
    

    /**
     * 根据auth_code获取用户的user_id和access_token
     * @param authCode
     * @return
     */
    public String getAccessToken(String authCode) {
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            return oauthTokenResponse.getAccessToken();
        } catch (Exception e) {
            log.error("使用authCode获取信息失败！", e);
            return null;
        }
    }

    /**
     * 根据access_token获取用户信息
     * @param token
     * @return
     */
    public AlipayUser getUserInfoByToken(String token) {
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest ();
        try {
            AlipayUserInfoShareResponse response =  alipayClient.execute(request, token);
            if (response.isSuccess()) {
                //封装支付宝对象信息
                AlipayUser alipayUser = new AlipayUser();
                String sk = IdUtil.fastSimpleUUID();
                alipayUser.setSk(sk);
                alipayUser.setGender(response.getGender());
                alipayUser.setOpenid(response.getUserId());
                alipayUser.setUserType(UserTypeEnums.ALI.getCode());
                alipayUser.setAddress(response.getAddress());
                alipayUser.setCertNo(response.getCertNo());
                alipayUser.setCity(response.getCity());
                alipayUser.setCollegeName(response.getCollegeName());
                alipayUser.setDegree(response.getDegree());
                alipayUser.setMobile(response.getMobile());
                alipayUser.setPhone(response.getPhone());
                alipayUser.setProvince(response.getProvince());
                alipayUser.setUserName(response.getUserName());
                alipayUser.setNickName(response.getNickName());
                return alipayUser;
            }
            log.error("根据 access_token获取用户信息失败!");
            return null;
        } catch (Exception e) {
            log.error("根据 access_token获取用户信息抛出异常！", e);
            return null;
        }
    }

	public String getOAuth2URL(String sc){
		String params = sc != null ? "?sc="+sc : null;
		return props.getRedirectUri(params);
	}

	

	public AlipayUser getUser(ALIPayOAuthLoginRequest request) {
		AlipayUser user = null;
		String authCode = request.getAuth_code();
		String accessToken = this.getAccessToken(authCode);
		if(accessToken != null){
			user = this.getUserInfoByToken(accessToken);
		}
		return user;
	}

	public void login(OTherUserResponse user, String sk) {
		
		String openId = user.getOpenid();
		if(StringUtils.isNotBlank(openId)){
			String sign = SecureUtil.md5(sk + "_" + user.getOpenid()).toUpperCase();
			ValueOperations<String, String> ops = redis.opsForValue();
			ops.set(sign, JSON.toJSONString(user),60 * 60,TimeUnit.SECONDS);
		}
	}
	
	public String getUIPath(String sc) {
		if(StringUtils.isNotBlank(sc)){
			return props.getUiPayPath();
		}else{
			return props.getUiIndexPath();
		}
	}
}
